package socket;

import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class Client {
    private Socket socket;
    public Client(){
        try {
            socket=new Socket("176.125.111.237",8088);//176.125.111.225
            System.out.println("服务器连接成功");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    public  void start(){
        try {
            ServerHandler handler = new ServerHandler();
            Thread t = new Thread(handler);
            t.start();


            OutputStream out = socket.getOutputStream();
            OutputStreamWriter osw = new OutputStreamWriter(out, StandardCharsets.UTF_8);
            BufferedWriter bw = new BufferedWriter(osw);
            PrintWriter pw =new PrintWriter(bw,true);

            Scanner scan = new Scanner(System.in);
            while (true){
                System.out.println("请输入昵称");
                String nickName = scan.nextLine();
                if (nickName.trim().isEmpty()){
                    System.out.println("昵称不能为空");
                }else {
                    pw.println(nickName);
                    break;
                }
            }



            while (true){
                String line = scan.nextLine();
                if ("exit".equalsIgnoreCase(line)){
                    break;
                }
                pw.println(line);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            try {
                socket.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    public static void main(String[] args) {
        Client client = new Client();
        client.start();
    }


    private  class ServerHandler implements Runnable{

        @Override
        public void run() {
            try {
                InputStream in = socket.getInputStream();
                InputStreamReader isr = new InputStreamReader(in,StandardCharsets.UTF_8);
                BufferedReader br = new BufferedReader(isr);
                String message;
                while ((message=br.readLine())!=null){
                    System.out.println(message);
                }
            } catch (IOException e) {
            }
        }
    }


}
